from flask import render_template,redirect,url_for,session, request, jsonify
from flask_login import login_user, login_required, logout_user, current_user

from bson.objectid import ObjectId

from model.requirement import RequirementDao
from service.sprint import SprintService
from service.requirement import RequirementService, RequirementForm

from controller import app

import json


@app.route('/sprint_view/<string:sprint_id>')
@app.route('/sprint_view/<string:sprint_id>', methods=['GET','POST'])
@login_required
def sprint_view(sprint_id):
    '''When a user logs in, their session is marked as 'fresh'.
    '''
    # Get sprint list belong to a project
    serv = SprintService()
    project_oid = serv.get_project_oid(sprint_id)
    _sprints = serv.get_sprints({'project_id':project_oid})
    
    if _sprints == []:
        return render_template('requirements.html', sprints=[], requirements=[], errors_json=[])
    else:
        requirement_serv = RequirementService()
        _query = {'sprint_id':ObjectId(sprint_id)}
        _requirements = requirement_serv.get_requirements(query=_query)
        _defaults = {'project_id':str(project_oid), 'sprint_id':sprint_id}
        if _requirements == []:
            return render_template('sprint_view.html', sprints=json.dumps(_sprints), requirements=[], defaults=json.dumps(_defaults))
        else:
            return render_template('sprint_view.html', sprints=json.dumps(_sprints), requirements=json.dumps(_requirements), defaults=json.dumps(_defaults))

@app.route('/requirement_view2/<string:requirement_id>')
@app.route('/requirement_view2/<string:requirement_id>', methods=['GET','POST'])
@login_required
def requirement_view2(requirement_id):
    # Get sprint list belong to a project
    serv = RequirementService()
    sprint_oid = serv.get_sprint_oid(requirement_id)
    _requirements = serv.get_sprints({'sprint_id':sprint_oid})
    
    if _requirements == []:
        return render_template('requirement_view.html', requirements=[], errors_json=[])
    else:
        '''
        requirement_serv = RequirementService()
        _query = {'sprint_id':ObjectId(requirement_id)}
        _requirements = requirement_serv.get_requirement(query=_query)
        '''
        _defaults = {'sprint_id':str(sprint_oid), 'requirement_id':requirement_id}
        if _requirements == []:
            return render_template('sprint_view.html', requirements=json.dumps(_requirements),  defaults=json.dumps(_defaults))
        else:
            return render_template('sprint_view.html', requirements=json.dumps(_requirements),  defaults=json.dumps(_defaults))

    


""" The following are Ajax handlers
"""
@app.route('/submit_requirement', methods=['GET','POST'])
@login_required
def submit_requirement():
    form = RequirementForm()
    if form.is_submitted():
        if form.has_error():
            return jsonify(errors=json.dumps(form.errors))
        else:
            service = RequirementService()
            service.submit_requirement(form.input, form.mode)
            return jsonify(errors=[])

@app.route('/checkin_requirements', methods=['GET','POST'])
@login_required
def checkin_requirements():
    ids = json.loads(request.values['json_ids'])
    serv = RequirementService()
    _requirements = serv.check_in(ids)
    return jsonify(requirements=_requirements)

@app.route('/checkout_requirements', methods=['GET','POST'])
@login_required
def checkout_requirements():
    ids = json.loads(request.values['json_ids'])
    sprint_id = request.values['sprint_id']
    serv = RequirementService()
    _requirements = serv.check_out(ids, sprint_id)
    return jsonify(requirements=_requirements)


@app.route("/get_requirements")
@app.route("/get_requirements", methods=['GET','POST'])
@login_required
def get_requirements():
    in_backlog = int(request.values['in_backlog'])
    if in_backlog == 1:
        sid = request.values['project_id']
        serv = RequirementService()
        _requirements = serv.get_requirements({'project_id':sid, 'in_backlog': 1})
        return jsonify(requirements=json.dumps(_requirements))
    else:
        sid = request.values['sprint_id']
        serv = RequirementService()
        _requirements = serv.get_requirements({'sprint_id':sid, 'in_backlog': 0})
        return jsonify(requirements=json.dumps(_requirements))
    

        
@app.route('/get_requirement')
@app.route('/get_requirement', methods=['GET','POST'])
@login_required
def get_requirement():
    sid = request.values['sid']
    serv = RequirementService()#{'project_id':})
    requirement = serv.get_requirement(sid)
    return jsonify(requirement=json.dumps(requirement))


@app.route('/delete_requirements')
@app.route('/delete_requirements', methods=['GET','POST'])
def delete_requirements():
    sid = request.values['sid']
    serv = RequirementService()
    serv.delete_requirement(sid)
    _requirements = serv.get_requirements()
    
    return jsonify(requirements=json.dumps(_requirements))


@app.route('/get_tree_datas')
@app.route('/get_tree_datas', methods=['GET','POST'])
@login_required
def get_tree_datas():
    serv = RequirementService()
    tree_datas = serv.get_backlog_tree()
    return jsonify(trees=json.dumps(tree_datas)) 